package cn.yudao.ymcc.mq.listener;

import cn.yudao.ymcc.domain.CourseOrder;
import cn.yudao.ymcc.domain.PayFlow;
import cn.yudao.ymcc.domain.PayOrder;
import cn.yudao.ymcc.dto.AliPayNotifyMqDto;
import cn.yudao.ymcc.dto.Order2PayTranMesDto;
import cn.yudao.ymcc.service.IAlipayNotifyService;
import cn.yudao.ymcc.service.IPayFlowService;
import cn.yudao.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
@RocketMQTransactionListener(txProducerGroup ="txPayOrderCourse")
public class AliPayNotifyListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IAlipayNotifyService alipayNotifyService;

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IPayFlowService payFlowService;

    // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        Map<String, Object> map = (Map<String, Object>) o; // 得到订单信息--执行本地事务
        // 执行本地事务
        try {
            boolean success = alipayNotifyService.updatePayOrderInsertPayFlow(map);
            if (success){
                return RocketMQLocalTransactionState.COMMIT;

            }else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    // 检查本地事务状态
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            // 获取传入的信息
            byte[] payload = (byte[]) message.getPayload();
            String s = new String(payload, StandardCharsets.UTF_8);
            AliPayNotifyMqDto aliPayNotifyMqDto = JSONObject.parseObject(s, AliPayNotifyMqDto.class);
            PayOrder payOrder = payOrderService.getPayOrder(aliPayNotifyMqDto.getOrderNo());
            PayFlow payFlow = payFlowService.selectByOrder(aliPayNotifyMqDto.getOrderNo());
            if (payOrder.getPayStatus() == PayOrder.SUCCESS_STATUS && payFlow != null){
                return RocketMQLocalTransactionState.COMMIT;
            }else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }

        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
